// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const log = cloud.logger()
const db = cloud.database()
function createGroup(openId,{timer,startTime,endTime,description,count}){
    return new Promise((resolve,reject)=>{
        db.collection("groupAction").add({
            data:[{
                _openid:openId,
                timer:new Date(timer),
                startTime:new Date(startTime),
                endTime:new Date(endTime),
                description,
                count,
                allready:1,
                isDone:0,
                member:[]
              }]
        }
        )
          .then(res => {
            cloud.callFunction({
                name:"examineGroup",
                data:{
                    id:res._ids[0],
                    startTime
                  }
            })
            resolve({
                code:200,
                data:res
            })
          })
          .catch((errr)=>{
                reject({
                    code:401,
                    msg:errr
                })
          })
    })
}
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    if(event.count<=1){
        return {
            code:401,
            msg:"The condition for activate group is that the number of attending  members must greater than one!"
        }
    }
    let res =await createGroup(wxContext.OPENID,event)
    return res
}